<template>
    <MkDrawer ref="drawerRef" headerButton="none" title="数据维护">
        <template #btn>
            <el-button type="primary" @click="query">仅查询</el-button>
            <el-button type="primary" @click="execute">执行</el-button>
        </template>
        <MkForm :model="r.model" ref="mkFormRef" :col="3">
            <el-container>
                <el-aside>
                    <MkInput label="p1" v-model="r.model.p1" required="true" />
                    <MkInput label="p2" v-model="r.model.p2" />
                    <MkInput label="p3" v-model="r.model.p3" />
                </el-aside>
                <el-main style="padding: 0px 0px 0px 8px;">
                    <MkInput label="标题" v-model="r.model.title" required="true" :col="2" />
                    <MkInput label="说明" v-model="r.model.remark" required="true" :rows="3" type="textarea" :col="2" />
                </el-main>
            </el-container>
        </MkForm>
        <el-tabs type="border-card" v-model="editableTabsValue">
            <el-tab-pane label="查询SQL">
                <v-ace-editor v-model:value="r.model.sql1" lang="sql" theme="terminal" :min-lines="30" :maxLines="1000"
                    :style="editStyle" />
            </el-tab-pane>
            <el-tab-pane label="修改SQL" name="sql2">
                <v-ace-editor v-model:value="r.model.sql2" lang="sql" theme="terminal" :min-lines="30" :maxLines="1000"
                    :style="editStyle" />
            </el-tab-pane>
            <el-tab-pane label="模板">
                <v-ace-editor v-model:value="r.model.template" lang="html" theme="terminal" :min-lines="30"
                    :maxLines="1000" :options="aceConfig" />
            </el-tab-pane>
            <el-tab-pane label="预览" style="min-height: 100px;" :loading="r.loading">
                <div style=" border: 1px solid #dcdfe6">
                    <component :is="myComp"> </component>
                </div>
            </el-tab-pane>
        </el-tabs>
    </MkDrawer>
</template>

<script lang="ts" setup>
// 问卷分类新增，编辑
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
// 接口
import { BasPrintDraftApi, BasPrintDraftOutput } from '/@/api/bas/BasPrintDraft';
// 工具
import { isNull, clog, showSuccess, showError } from '/@/utils/index'

import { VAceEditor } from 'vue3-ace-editor';
import 'ace-builds/src-noconflict/mode-html'; // Load the language definition file used below
import 'ace-builds/src-noconflict/mode-sql'; // Load the language definition file used below
import 'ace-builds/src-noconflict/theme-terminal'; // Load the theme definition file used below
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/ext-searchbox';

const emits = defineEmits(['onSuccess']);

const mkFormRef = ref();
const drawerRef = ref();
const editableTabsValue = ref('2')

const editStyle = { fontSize: '14px' }

//ace编辑器配置
const aceConfig = {
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
    tabSize: 2,
    showPrintMargin: false,
    fontSize: 14,
    fontFamily: '"Consolas", "Lucida Console", "Courier New", "monospace"',
    //showGutter: true, //显示行号
    showLineNumbers: true, //显示行号
    showFoldWidgets: true, //显示折叠按钮
    //showInvisibles: true, //显示空白字符
    useWorker: false, //是否使用工作线程
    basePath: ""
}

const r = reactive({
    loading: false,
    model: {} as BasPrintDraftOutput,
});

// 打开弹窗
const open = async (row: any) => {
    drawerRef.value.show();
    mkFormRef.value?.resetFields();
    r.model = row;
};

//自定义组件
const myComp = ref()


const query = async () => {
    if (!validate()) return;
    await submit();
    editableTabsValue.value = '3'
    // 仅查询SQL1
    var res = await BasPrintDraftApi.queryOnly({ id: r.model.id, p1: r.model.p1, p3: r.model.p2, p2: r.model.p3 })
    showResult(res);
}

const execute = async () => {
    if (!validate()) return;
    await submit();
    editableTabsValue.value = '3'
    // 会执行所有的SQL
    var res = await BasPrintDraftApi.queryDataAndTemplate({ id: r.model.id, p1: r.model.p1, p3: r.model.p2, p2: r.model.p3 })
    showResult(res);
}

const submit = async () => {
    // 校验
    if (!validate()) return;
    // 保存
    r.model.sql3 = r.model.sql1;
    await BasPrintDraftApi.update(r.model);
    //showSuccess();
    emits('onSuccess');
}

// 预览
const showResult = async (res: any) => {
    try {
        r.loading = true;
        myComp.value = {
            setup() {
                return {
                    t1: res.data.t1,
                    t2: res.data.t2,
                    t3: [], t4: [], t5: []
                };
            },
            template: `${r.model.template}`
        }
        r.loading = false;
    } catch (error: any) {
        r.loading = false;
        showError("捕获到异常: " + error.message)
        console.error('捕获到异常:', error.message);
    }
}

const validate = () => {
    if (isNull(r.model.title) || isNull(r.model.template) || isNull(r.model.sql1) || isNull(r.model.p1) || isNull(r.model.remark)) {
        ElMessage.error(" 标题、模板、SQL1、P1、说明 不能为空");
        return false;
    }
    return true;
}

// 导出对象
defineExpose({ open });
</script>
